<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
import { Ref, computed, onMounted, ref, watch } from "vue";
import Http from "./lib/Http";
import { System } from "./lib/types";
import { setStyle, setWindowFunction } from "./lib";
type PromptCode = {
  code: string,
  pageId: number
}
export type DomResult = Dom & { value?: string }
export interface Dom {
  id: number
  name: string
  refStr: string
  type: 'button' | 'input' | 'moduleEntrance' | 'virtualDom' | 'data'
  keywords: string[]
  pageId?: number
  relatePageId: number
  code: string
}
const systemId = 1
const systemUrl = 'http://stock.cloudling.cn/static/index.html#/login'

const lastInputTime = ref(0)
let webview: any = null

const evaluateCodes = async (domResults: DomResult[]) => {
  for (const dom of domResults) {
    let code = ''
    if (dom.type == 'data') {
      (window as any).domValue = dom.value;
      eval(`
      (async () => {
      try{
        ${dom.code}
      }catch(err){
        console.log('代码执行失败'+err)
      }
    })();
      `)
      continue
    }
    if (dom.type == 'virtualDom') {
      code = dom.code
    }
    if (dom.type == 'button' || dom.type == 'moduleEntrance') {
      code =
        `
      f_dom('${dom.refStr}').click();
      await f_wait(300);
      `
    }
    if (dom.type == 'input') {
      code =
        `
      f_set(f_dom('${dom.refStr}'),'${dom.value}');
      await f_wait(300);
      `
    }

    let evalJs = `
    (async () => {
      try{
        ${code}
      }catch(err){
        console.log('代码执行失败'+err)
      }
    })();
    `

    console.log(`执行的js代码${evalJs}`)
    await webview.executeJavaScript(evalJs);
  }

  setTimeout(() => {
    setWindowFunction(webview)
  }, 2000)

}
onMounted(async () => {

  webview = document.getElementById("webview") as any
  webview.addEventListener('dom-ready', () => {
    setWindowFunction(webview)
    setStyle(webview)
  });

  setInterval(() => {
    const now = new Date().getTime()
    if (status.value == 1 && text.value != '' && lastInputTime.value > 0 && now - lastInputTime.value > 2000) {
      console.log('send')
      doSendText()
    }
  }, 1000)


});

const Api = (window as any).electronAPI;

(window as any).f_ai = (text:string,data:string)=>{
      setDataLoading()
      Http.post<string>('/api/client/data',{text,data}).then(res=>{
        if(res){
          setDataContent(res)
        }
      })
}

let pageId = 0
const doSendText = () => {
  sendText.value = text.value
  text.value = ''
  status.value = 2
  Http.post<DomResult[]>('/api/client/evaluate', { text: sendText.value, pageId, systemId }).then(res => {
    if (res) {
      if (res.length > 0) {
        evaluateCodes(res)
        setReply('已执行相关操作')
      } else {
        setReply('抱歉，不是很明白您的意思，请详细说明')
      }
    } else {
      setReply('抱歉，网络有些问题请稍后再试')
    }
  })

}
const replyText = ref('')
const setReply = (str: string) => {
  status.value = 3
  replyText.value = str
  Api.say(replyText.value)

  setTimeout(() => {
    startRecord()
  }, 8000)
}


const changeInput = (e) => {
  const now = new Date().getTime()
  lastInputTime.value = now
}
const text = ref('')
watch(text, (v, ov) => {
  console.log(v)
})
const onInput = () => {
  const now = new Date().getTime()
  hideData()
  lastInputTime.value = now
}


const status = ref(0)

const startRecord = () => {
  status.value = 1
  setTimeout(() => {
    document.getElementById('myInput')?.focus()
  }, 300)
}

const sendText = ref('')
const webviewContent = computed(() => {
  return `
<webview id="webview" src="${systemUrl}" style="height: 100vh;width: 100vw;left: 0px;top: 0px;" ></webview>

`
})

const dataStatus = ref(0)
const dataContent = ref('')
const setDataLoading = ()=>{
  dataStatus.value = 1;
}
const setDataContent = (str:string)=>{
  if(dataStatus.value>0){
    dataStatus.value = 2
    dataContent.value = str
  }
}

const hideData = ()=>{
  dataStatus.value = 0
}
</script>

<template>
  <div style="position: relative;width: 100vw;height: 100vh; left: 0px; top: 0px;">
    <div style="position: absolute; left: 0px; bottom: 0px;" v-html="webviewContent">
    </div>
  </div>
  <div class="dataReply" v-if="dataStatus>0">
    <div style="margin-top: 6vh;" v-if="dataStatus==1">
        <VueSpinnerOval size="50" color="#3e566199" />
        <div style="margin-top: 10px;">正在分析数据</div>
      </div>
      <div style="margin: 20px;text-align: left;" v-if="dataStatus==2">
        {{ dataContent }}
      </div>
  </div>
  <div class="bottom">
    <div class="recording" v-if="status == 1">
      <div style="margin-right: 20px;">
        <VueSpinnerComment size="50" color="#3e566199" />
      </div>
      <textarea @input="onInput" class="input" @change="changeInput" id="myInput" v-model="text" />
    </div>

    <div class="start" v-if="status == 0">
      <button class="btn" @click="startRecord">开启语音会话</button>
    </div>

    <div class="sending" v-if="status == 2">
      <div class="sendText">{{ sendText }}</div>
      <div style="margin-top: 20px;">
        <VueSpinnerBeat size="50" color="rgb(16,82,113)" />
      </div>
    </div>

    <div class="reply" v-if="status == 3">
      <div class="replyText">{{ replyText }}</div>
    </div>



  </div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin: 0px;
}

body,
html {
  margin: 0px;
}

img {
  margin: 5px;
}

.recording {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.bottom {
  position: fixed;
  left: 30vw;
  width: 40vw;
  height: 10vh;
  bottom: 50px;
  background-color: #ffffff99;
  display: block;
  backdrop-filter: blur(15px);
  border-radius: 10px;
  padding: 20px 10px;
  box-shadow: 2px 2px 5px 1px #cccccc99;
}

.dataReply {
  position: fixed;
  left: 30vw;
  width: 40vw;
  height: 20vh;
  top:20vh;
  background-color: #ffffff99;
  display: block;
  backdrop-filter: blur(15px);
  border-radius: 10px;
  padding: 20px 10px;
  box-shadow: 2px 2px 5px 1px #cccccc99;
}


.input {
  background-color: transparent;
  width: 30vw;
  font-size: 1.5vw;
  max-height: 8vh;
  overflow: scroll;
  scrollbar-width: none;
  border: 1px solid #cccccc;
  padding: 10px;
  color: #222;
}

.input:focus {
  outline: none;
  border: 1px solid #3e566166;
  /* 设置边框样式 */
}

.plugins {
  font-size: 20px;
  font-weight: bold;
  margin-top: 20px;
}

.btn {
  background-color: #3e5661cc;
  border: none;
  color: white;
  font-size: 1.3vw;
  padding: 10px 20px;
  margin-top: 20px;
  border-radius: 10px;
  cursor: pointer;
}

.sending {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.sending .sendText {
  font-size: 1.2vw;
}

.reply {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
